package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.TBProductType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.TBCustomer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TBProductTypeMapper;
import com.ruoyi.system.service.ITBProductTypeService;

import javax.validation.Validator;

/**
 * 产品类型Service业务层处理
 * 
 * @author pspyy
 * @date 2022-02-25
 */
@Service
public class TBProductTypeServiceImpl implements ITBProductTypeService 
{
    private static final Logger log = LoggerFactory.getLogger(TBProductTypeServiceImpl.class);
    @Autowired
    private TBProductTypeMapper tBProductTypeMapper;


    @Autowired
    protected Validator validator;
    /**
     * 查询产品类型
     * 
     * @param id 产品类型主键
     * @return 产品类型
     */
    @Override
    public TBProductType selectTBProductTypeById(Long id)
    {
        return tBProductTypeMapper.selectTBProductTypeById(id);
    }

    /**
     * 查询产品类型列表
     * 
     * @param tBProductType 产品类型
     * @return 产品类型
     */
    @Override
    public List<TBProductType> selectTBProductTypeList(TBProductType tBProductType)
    {
        List<TBProductType> tbProductTypes = tBProductTypeMapper.selectTBProductTypeList(tBProductType);
        for (TBProductType p:tbProductTypes) {
            if(p.getParentProductId() != 0){
                TBProductType tbProductType = tBProductTypeMapper.selectTBProductTypeById(p.getParentProductId());
                if(tbProductType!=null){
                    p.setParentProductName(tbProductType.getProductName());
                }
            }
        }
        return tbProductTypes;
    }

    @Override
    public List<TBProductType> buildProductTree(List<TBProductType> productTypes) {
        List<TBProductType> returnList = new ArrayList<TBProductType>();
        List<Long> tempList = new ArrayList<Long>();
        for (TBProductType productType : productTypes)
        {
            tempList.add(productType.getId());
        }
        for (Iterator<TBProductType> iterator = productTypes.iterator(); iterator.hasNext();)
        {
            TBProductType productType = (TBProductType) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(productType.getParentProductId()))
            {
                recursionFn(productTypes, productType);
                returnList.add(productType);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = productTypes;
        }
        return returnList;
    }

    private void recursionFn(List<TBProductType> list, TBProductType t)
    {
        // 得到子节点列表
        List<TBProductType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TBProductType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<TBProductType> getChildList(List<TBProductType> list, TBProductType t)
    {
        List<TBProductType> tlist = new ArrayList<TBProductType>();
        Iterator<TBProductType> it = list.iterator();
        while (it.hasNext())
        {
            TBProductType n = (TBProductType) it.next();
            if (StringUtils.isNotNull(n.getParentProductId()) && n.getParentProductId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TBProductType> list, TBProductType t)
    {
        return getChildList(list, t).size() > 0;
    }
    @Override
    public List<TreeSelect> buildProductTreeSelect(List<TBProductType> productTypes) {
        List<TBProductType> productTypeTrees = buildProductTree(productTypes);
        return productTypeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 新增产品类型
     * 
     * @param tBProductType 产品类型
     * @return 结果
     */
    @Override
    public int insertTBProductType(TBProductType tBProductType)
    {
        TBProductType info = tBProductTypeMapper.selectTBProductTypeById(tBProductType.getParentProductId());
        if(info!=null){
            tBProductType.setAncestors(info.getAncestors() + "," + tBProductType.getParentProductId());
        }else{
            tBProductType.setParentProductId(0l);
            tBProductType.setAncestors("0");
        }
        tBProductType.setCreateTime(DateUtils.getNowDate());
        return tBProductTypeMapper.insertTBProductType(tBProductType);
    }

    /**
     * 修改产品类型
     * 
     * @param tBProductType 产品类型
     * @return 结果
     */
    @Override
    public int updateTBProductType(TBProductType tBProductType)
    {
        TBProductType newParent = tBProductTypeMapper.selectTBProductTypeById(tBProductType.getParentProductId());
        TBProductType oldObj = tBProductTypeMapper.selectTBProductTypeById(tBProductType.getId());
        if (StringUtils.isNotNull(newParent) && StringUtils.isNotNull(oldObj))
        {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = oldObj.getAncestors();
            tBProductType.setAncestors(newAncestors);
            updateProductTypeChildren(tBProductType.getId(), newAncestors, oldAncestors);
        }
        tBProductType.setUpdateTime(DateUtils.getNowDate());
        int result = tBProductTypeMapper.updateTBProductType(tBProductType);
        return result;
    }

    /**
     * 修改子元素关系
     *
     * @param id 被修改的ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateProductTypeChildren(Long id, String newAncestors, String oldAncestors)
    {
        List<TBProductType> children = tBProductTypeMapper.selectChildrenProductTypeById(id);
        for (TBProductType child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            tBProductTypeMapper.updateProductChildren(children);
        }
    }

    /**
     * 批量删除产品类型
     * 
     * @param ids 需要删除的产品类型主键
     * @return 结果
     */
    @Override
    public int deleteTBProductTypeByIds(Long[] ids)
    {
        return tBProductTypeMapper.deleteTBProductTypeByIds(ids);
    }

    /**
     * 删除产品类型信息
     * 
     * @param id 产品类型主键
     * @return 结果
     */
    @Override
    public int deleteTBProductTypeById(Long id)
    {
        return tBProductTypeMapper.deleteTBProductTypeById(id);
    }

    @Override
    public int checkProductTypeNameUnique(String  productName) {
        return tBProductTypeMapper.checkProductTypeNameUnique(productName);
    }

    @Override
    public String selectIdByProductName(String productName) {
        return tBProductTypeMapper.selectIdByProductName(productName);
    }

    @Override
    public String importProductType(List<TBProductType> productTypeList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(productTypeList) || productTypeList.size() == 0)
        {
            throw new ServiceException("导入产品类型数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TBProductType productType : productTypeList)
        {
            try
            {
                // 验证是否存在这个产品类型
                TBProductType product = tBProductTypeMapper.selectProductByName(productType.getProductName());
                if (StringUtils.isNull(product))
                {
                    BeanValidators.validateWithException(validator, productType);
                    if("".equals(productType.getParentProductName()) || productType.getParentProductName() == null){
                        productType.setParentProductId(Long.parseLong("0"));
                    }else{
                        String s = tBProductTypeMapper.selectIdByProductName(productType.getParentProductName());
                        if(s != null){
                            productType.setParentProductId(Long.parseLong(s));
                        }else{
                            productType.setParentProductId(Long.parseLong("0"));
                        }
                    }
                    this.insertTBProductType(productType);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、产品类型 " + productType.getProductName() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、产品类型 " + productType.getProductName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、产品类型 " + productType.getProductName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public TBProductType selectProductTypeByName(String productName) {
        return null;
    }
}
